#include <QCoreApplication>
#include <QSqlError>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QDateTime>
#include <memory>
#include <vector>
#include "Note.h"

using namespace std;

shared_ptr<Note> createNote()
{
	shared_ptr<Note> note(new Note);
	note->setId(QUuid::createUuid());
	note->setContent("Hello");
	return note;
}

vector<shared_ptr<Note>> createNotes()
{
	vector<shared_ptr<Note>> notes;
	notes.push_back(createNote());
	return notes;
}

int addData()
{
	vector<shared_ptr<Note>> notes = createNotes();
	QString sql = "insert into Note(id,  parent, title, content, creatingTime)values(:id, :parent, :title, :content,:creatingTime);";
	QSqlQuery query;
	query.prepare(sql);
	foreach(shared_ptr<Note> note, notes)
	{
		query.bindValue(":id", note->id().toRfc4122());
		query.bindValue(":parent", note->parent());
		query.bindValue(":content", note->content());
		query.bindValue(":creatingTime", QDateTime::currentDateTime());
		if (query.exec())
			return 0;
		qDebug() << "insert data failed." << query.lastError();
	}
	return 1;
}

void showData()
{
	QString sql = "select * from Note order by creatingTime desc";
	QSqlQuery query;
	query.prepare(sql);
	if (!query.exec())
		return;
	while(query.next())
	{
		Note note;
		note.setId(QUuid::fromRfc4122(query.value(Note::ID).toByteArray()));
		note.setParent(query.value(Note::PARENT).toByteArray());
		note.setContent(query.value(Note::CONTENT).toByteArray());
		qDebug() << "ID:" << note.id() 
			<< "\nParent:" << note.parent().toRfc4122()
			<< "\nCotent:" << note.content()
			<< "\nTime:" << query.value(Note::CREATINGTIME);

	}

}



int main(int argc, char** argv)
{
	QCoreApplication a(argc, argv);
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
	db.setDatabaseName("Personal.db");
	if (!db.open())
	{
		qDebug() << "open database failed.";
		return 0;
	}
	QString sql = "create table if not exists Note(id char(16) primary key, parent char(16), title nchar(100), content binary blob, creatingTime datetime not null);"; 
	QSqlQuery query;
	query.prepare(sql);
	if (!query.exec())
	{
		qDebug() << query.lastError();
		qDebug() << "create database failed."; 
		return 0;
	}
	int ret = addData();
	showData();
	return ret;
}
